<?php

/**
 * User: hda
 * Date: 2017/4/25
 * Time: 9:57
 * Progress: 0%
 */

namespace icontroller\wechat;

use library\tencent\wechat\wechat_index\SdkConfig;
use think\Config;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;

abstract class AController extends Controller
{

    protected $account_id;
    protected $account;
    protected $jssdk;

    protected $beforeActionList = [
        "isLogin",
    ];
    function __construct()
    {
        parent::__construct();
        $request = Request::instance();
        if (!$request->isAjax()){
            $back_url = input("back_url", url("user/Index/index"));
            $c_url = $request->url();
//            Cookie::set('back_url', $c_url);
            $this->assign("c_url",$c_url);
            $this->assign("back_url",$back_url);
        }
    }

    public function isLogin(){
        $this->account_id = Cookie::get(Config::get('const.cookie_name_wechat'));

        if (!$this->account_id) {
          //  $parent_id = input('parent_id');
            $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

            Cookie::set('wechat_redirect_url', $url);
            //Cookie::set('parent_id', $parent_id);

            //$this->redirect('user/login/wechat');
           $this->redirect('user/login/index');
        }

        //全局添加微信信息
        $this->account = $this->get_account($this->account_id);
        $this->assign('account', $this->account);

        $this->jssdk = $this->get_js_sdk();
        $this->assign('js_sdk', $this->jssdk);
    }

    private function get_account($account_id)
    {
        return Db::name('account')
            ->alias('a')
            ->join('account_wechat aw', 'a.id=aw.account_id', 'INNER')
            ->join('account aa', 'a.parent_id=aa.id', 'LEFT')
            ->where('a.id', $account_id)
            ->field('a.*,aw.subscribe,aa.nick as parent_nick')
//            ->cache(60)
            ->find();
    }

    private function get_js_sdk()
    {
        $js_sdk = SdkConfig::jssdk();
        return $js_sdk;
    }
}